package com.fencing_squad.homo.slice;

import com.alibaba.fastjson.JSONObject;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.list.Post;
import com.fencing_squad.homo.map_util.util.PermissionsUtils;
import com.fencing_squad.homo.page.*;
import com.fencing_squad.homo.util.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.dcall.DistributedCallManager;
import ohos.security.SystemPermission;
import ohos.utils.PacMap;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainSlice extends AbilitySlice {
    private int currentPage = 0;
    private DirectionalLayout pageContainer;
    private Component welcomeImage;
    private Component offer;
    private Component receive;
    private Component community;
    private Component user;
    private Image offerIcon;
    private Image receiveIcon;
    private Image communityIcon;
    private Image userIcon;
    private Community communityPage = null;
    private Offer offerPage = null;
    private User userPage = null;
    private Receive receivePage = null;
    private Component communityComponent = null;
    private Component receiveComponent = null;
    private Component offerComponent = null;
    private Component userComponent = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_ability_main, null, false));

        initConfig();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void initConfig() {
        welcomeImage = findComponentById(ResourceTable.Id_welcome);
        offer = findComponentById(ResourceTable.Id_offer);
        receive = findComponentById(ResourceTable.Id_receive);
        community = findComponentById(ResourceTable.Id_community);
        user = findComponentById(ResourceTable.Id_user);
        offerIcon = (Image) findComponentById(ResourceTable.Id_offerIcon);
        receiveIcon = (Image) findComponentById(ResourceTable.Id_receiveIcon);
        communityIcon = (Image) findComponentById(ResourceTable.Id_communityIcon);
        userIcon = (Image) findComponentById(ResourceTable.Id_userIcon);
        pageContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_page);

        // 开屏动画
        AnimatorProperty property = AnimationConfig.getWelcomeAnim(welcomeImage);
        AnimationConfig.setInitAnimation(welcomeImage, property, null);

        // 页面切换实现
        offer.setClickedListener(this::change);
        receive.setClickedListener(this::change);
        community.setClickedListener(this::change);
        user.setClickedListener(this::change);

        PermissionsUtils permissionsUtils = PermissionsUtils.getInstance();
        // 获取权限
        String[] permissions = new String[2];
        permissions[0] = SystemPermission.LOCATION;
        permissions[1] = SystemPermission.DISTRIBUTED_DATASYNC;
        permissionsUtils.requestPermissions(this, permissions);

        // 加载首页
        offerPage = new Offer();
        offerComponent = offerPage.get(getContext(), this::selectImg, this::redirectToLogin);
        pageContainer.addComponent(offerComponent);
        offerPage.loadMap();

//        Timer timer = new Timer();
//        TimerTask timerTask = new TimerTask() {
//            @Override
//            public void run() {
//                call("13295823966");
//            }
//        };
//        timer.schedule(timerTask, 5000);
    }

    private void selectImg(int code) {
        requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"}, code);
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, code);
    }

    private void call(String number) {
        requestPermissionsFromUser(new String[]{"ohos.permission.PLACE_CALL"}, 114514);
        DistributedCallManager manager = DistributedCallManager.getInstance(this);
        System.out.println(manager.dial(number, false));
    }

    private void checkPostDetail(Object object) {
        Post post = null;
        if (object == null) {
            present(new StoreSlice(), new Intent());
            return;
        }
        if (object instanceof Post) {
            post = (Post) object;
        }
        if (post != null) {
            System.out.println(post.getContent());
            Intent intent = new Intent();
            intent.setParam("post_message_id", post.getId());
            present(new PostDetailSlice(), intent);
        }
    }

    private void handleUserClicked(Component component) {
        if(!Data.Account.isLogin) {
            redirectToLogin();
        }
        else {
            presentForResult(new UserDetailSlice(), new Intent(), 1);
        }
    }

    private void handlePostClicked(Component component) {
        if(!Data.Account.isLogin) {
            redirectToLogin();
        }
        else {
            presentForResult(new UserPostSlice(), new Intent(), 2);
        }
    }

    private void handleBalanceClicked(Component component) {
        if(!Data.Account.isLogin) {
            redirectToLogin();
        }
        else {
            presentForResult(new UserBalanceSlice(), new Intent(), 3);
        }
    }

    private void handleOfferClicked(Component component) {
        if(!Data.Account.isLogin) {
            redirectToLogin();
        }
        else {
            presentForResult(new UserOfferSlice(), new Intent(), 4);
        }
    }

    private void redirectToLogin() {
        presentForResult(new GuideSlice(), new Intent(), 0);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == 0) {
            if(Data.Account.isLogin) {
                Network.get("/user", this::resolve, this::reject);
            }
        }
        else if (requestCode == 1){
            userPage.update();
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 200) {
            communityPage.setImageURI(resultData.getUriString());
        }
        else if (requestCode == 201) {
            offerPage.setImageURI(resultData.getUriString());
        }
    }

    private void resolve(JSONObject res) {
        Data.Account.getFromJSON(res.getJSONObject("data"));
        if (userPage != null) {
            userPage.update();
        }
    }

    private void reject(int code, String message) {
        System.out.println(message);
    }

    private void change(Component component) {
        int index = getIndex(component.getId());
        if(index != currentPage) {
            setUnselected(currentPage);
            setSelected(index);
            currentPage = index;
            switchPage(index);
        }
        else {
            if (index == 2 && communityPage != null) {
                communityPage.refresh();
            }
        }
    }

    /*
    * 切换页面
    * */
    private void switchPage(int index) {
        switch (index) {
            case 0:
                pageContainer.removeAllComponents();
                pageContainer.addComponent(offerComponent);
                offerPage.mapReload();
                break;
            case 1:
                if (receivePage == null) {
                    receivePage = new Receive();
                }
                if (receiveComponent == null) {
                    receiveComponent = receivePage.get(this, this::redirectToLogin, this::checkOfferDetail);
                }
                pageContainer.removeAllComponents();
                pageContainer.addComponent(receiveComponent);
                break;
            case 2:
                if (communityPage == null) {
                    communityPage = new Community();
                }
                if (communityComponent == null) {
                    communityComponent = communityPage.get(this, this::checkPostDetail, this::selectImg, this::redirectToLogin);
                }
                pageContainer.removeAllComponents();
                pageContainer.addComponent(communityComponent);
                break;
            case 3:
                if (userPage == null) {
                    userPage = new User();
                }
                if (userComponent == null) {
                    userComponent = userPage.get(this, this::handleUserClicked, this::handlePostClicked, this::handleBalanceClicked, this::handleOfferClicked, this::redirectToLogin);
                }
                pageContainer.removeAllComponents();
                pageContainer.addComponent(userComponent);
                userPage.update();
                break;
            default:
                break;
        }
    }

    private void setUnselected(int index) {
        switch (index){
            case 0: offerIcon.setPixelMap(ResourceTable.Media_offer);break;
            case 1: receiveIcon.setPixelMap(ResourceTable.Media_receive);break;
            case 2: communityIcon.setPixelMap(ResourceTable.Media_community);break;
            case 3: userIcon.setPixelMap(ResourceTable.Media_user);break;
        }
    }

    private void setSelected(int index) {
        switch (index){
            case 0: offerIcon.setPixelMap(ResourceTable.Media_offer_selected);break;
            case 1: receiveIcon.setPixelMap(ResourceTable.Media_receive_selected);break;
            case 2: communityIcon.setPixelMap(ResourceTable.Media_community_selected);break;
            case 3: userIcon.setPixelMap(ResourceTable.Media_user_selected);break;
        }
    }

    private int getIndex(int id) {
        switch (id){
            case ResourceTable.Id_offer:return 0;
            case ResourceTable.Id_receive: return 1;
            case ResourceTable.Id_community: return 2;
            case ResourceTable.Id_user: return 3;
            default: return -1;
        }
    }

    public void checkOfferDetail(String rewardId) {
        Intent intent = new Intent();
        intent.setParam("rewardId", rewardId);
        present(new SupervisorSlice(), intent);
    }
}
